import React, { createElement, FC, useMemo } from 'react';
import { InputNumber } from 'antd';

enum EInputNumberFormat {
  'Number' = 1,
  'Percent' = 2,
}

export const BaseFieldInputNumber: FC<any> = (props) => {
  const {
    columnConfig,
    validateConfig,
    style,
    className,
    value,
    onChange,
    inputNumberProps,
    ...otherProps
  } = props;

  // 百分比处理
  const percentProps: any = useMemo(() => {
    const isPercent = columnConfig?.format === EInputNumberFormat.Percent;

    // 是否开启千分位置
    const isThousands = columnConfig?.thousands == 1;
    // 小数位
    const decimalPlace = columnConfig?.decimalPlace || 0;
    if (isPercent) {
      return {
        formatter: (values: string) => {
          if (values === undefined || isNaN(parseFloat(values))) {
            return '';
          }
          const formattedValue = parseFloat(values).toFixed(decimalPlace);
          const decimalRegex = /\.?0*$/; // 匹配末尾都是零的小数部分
          return `${formattedValue.replace(decimalRegex, '')}%`;
        },
        parser: (values: string) => values?.replace('%', ''),
      };
    }

    // 显示千分位
    if (isThousands) {
      return {
        formatter: (values: string) => {
          if (!values) return '';
          const [integer, decimal] = String(values).split('.'); // 分割整数和小数部分
          return `$ ${integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}${
            decimal !== undefined ? `.${decimal}` : ''
          }`;
        },
        parser: (values: string) => values!.replace(/\$\s?|(,*)/g, ''), // 只去掉 "$" 和 ","
        precision: decimalPlace,
      };
    }

    return {
      formatter: (values: any) => {
        if (values === undefined) return '0';
        const factor = Math.pow(10, decimalPlace);
        return (Math.floor(values * factor) / factor).toString();
      },
      parser: (values: string) => {
        if (!values) return 0;
        const factor = Math.pow(10, decimalPlace);
        return Math.floor(parseFloat(values) * factor) / factor;
      },
    };
  }, [columnConfig?.format]);
  // 设置数字范围
  const range = useMemo(() => {
    return { min: validateConfig?.numberRange?.min, max: validateConfig?.numberRange?.max };
  }, [validateConfig?.numberRange]);

  return (
    <InputNumber
      className={className}
      style={{ width: '100%', ...style }}
      {...otherProps}
      {...inputNumberProps}
      value={value}
      onChange={onChange}
      {...percentProps}
      {...range}
    />
  );
};
